const fm = wx.getFileSystemManager()

export const access = async (filePath) => {
	return new Promise((resolve, reject) => {
		fm.access({
			path: filePath,
			success: (res) => {
				if (res.errMsg && res.errMsg == 'access:ok') {
					resolve({ success: true })
				} else {
					reject({ success: false, msg: '路径访问失败' })
				}
			},
			fail: (err) => {
				if (err.errMsg.indexOf('access:fail no such file or directory, access') != -1) {
					fm.mkdir({
						dirPath: filePath,
						recursive: true,
						success: (res) => {
							console.log('%c [ res ]-20', 'font-size:13px; background:pink; color:#bf2c9f;', res)
							resolve({ success: true })
						},
						fail: (error) => {
							reject({ success: false, msg: error.errMsg })
						},
					})
				} else {
					reject({ success: false, msg: err.errMsg })
				}
			},
		})
	})
}

export const downloadFile = async (url, filePath) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			filePath,
			success: (res) => {
				if (res.statusCode == 200) {
					resolve({ success: true, ...res })
				} else {
					reject({ success: false, msg: '下载图片失败' })
				}
			},
			fail: (err) => {
				reject({ success: false, msg: err.errMsg })
			},
		})
	})
}

export const saveImageToPhotosAlbum = async (filePath) => {
	return new Promise((resolve, reject) => {
		uni.saveImageToPhotosAlbum({
			filePath,
			success: (res) => {
				if (res.errMsg == 'saveImageToPhotosAlbum:ok') {
					resolve({ success: true, ...res })
				} else {
					reject({ success: false, msg: '保存图片失败' })
				}
			},
			fail: (err) => {
				reject({ success: false, msg: err.errMsg })
			},
		})
	})
}
